package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.History;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.LookLater;
import com.sk.bilibili.mapper.LookLaterMapper;

/**
* @author 邵康
* @date 2021/12/02 16:31
*/
@Service
public class LookLaterService extends ServiceImpl<LookLaterMapper,LookLater> {

    @Autowired
    private VideoSetService videoSetService;

    public R<Void> add(LookLater lookLater) {
        int memberId = BSessionUtils.getMemberId();
        QueryWrapper<LookLater> queryWrapper = QueryWrapperUtils.eq("member_id", memberId,
                "video_set_id", lookLater.getVideoSetId());
        if(getOne(queryWrapper,false)!=null)return R.error("不能重复添加");
        lookLater.setMemberId(memberId);
        save(lookLater);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(LookLater lookLater) {
        updateById(lookLater);
        return R.success();
    }

    public R<IPage<LookLater>> page(Integer page, Integer size) {
        QueryWrapper<LookLater> queryWrapper = QueryWrapperUtils.eq("member_id",
                BSessionUtils.getMemberId());
        IPage<LookLater> iPage = page(new Page<>(page, size), queryWrapper);
        iPage.getRecords().forEach(this::warpVideoSet);
        return R.success(iPage);
    }

    private void warpVideoSet(LookLater lookLater) {
        lookLater.getExtra().addExtra(videoSetService.getBaseVideoSet(lookLater.getVideoSetId()));
    }

    public R<Void> removeOver() {
        int memberId = BSessionUtils.getMemberId();
        QueryWrapper<LookLater> queryWrapper = QueryWrapperUtils.eq("member_id", memberId, "over", 1);
        remove(queryWrapper);
        return R.success();
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.HistoryService.add'")
    public void handleVideoSetWatch(BiliBiliEvent<History> event){
        History history = event.getData();
        if(history.getType()!=0)return;
        baseMapper.overLookLater(history.getMemberId(),history.getTargetId());
    }

}
